<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>simpleChat</title>
    <meta content="width=device-width, initial-scale=1.0,
 minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">
    <title>chat</title>
    <script src="../libs/vue/dist/vue.min.js" type="text/javascript"></script>
    <link href="../libs/iview/dist/styles/iview.css" rel="stylesheet" type="text/css">
    <script src="../libs/iview/dist/iview.min.js" type="text/javascript"></script>
    <script src="../libs/axios/dist/axios.min.js" type="text/javascript"></script>
    <style scoped>
        [v-cloak] {
            display: none;
        }

        html, body {
            width: 100%;
            height: 100%;
            margin: 0px;
            padding: 0px;
        }

        #app {
            height: 100%;
        }

        .chat-box {
            margin: 0 auto;
            background: #fafafa;
            position: absolute;
            height: 100%;
            width: 100%;
            /*max-width: 700px;*/
        }

        header {
            position: fixed;
            width: 100%;
            height: 1rem;
            background: #409eff;
            /*max-width: 700px;*/
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;

        }

        .msg-box {
            position: absolute;
            height: calc(100% - 3rem);
            width: 100%;
            margin-top: 1.25rem;
            overflow-y: scroll;
        }

        .msg {
            width: 95%;
            min-height: 2.5rem;
            margin: 1rem 0.5rem;
            position: relative;
            display: flex;
            justify-content: flex-start !important;
        }

        .user-head {
            min-width: 2.5rem;
            width: 2.5rem;
            height: 2.5rem;
            border-radius: 50%;
            background: #f1f1f1;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .head {
            width: 1.2rem;
            height: 1.2rem;
        }

        .user-msg {
            width: 80%;

            word-break: break-all;
            position: relative;
            z-index: 5;
        }


        .left {
            background: white;
            animation: toLeft 0.5s ease both 1;
        }

        .right {
            background: #53a8ff;
            color: white;
            animation: toright 0.5s ease both 1;
        }

        @keyframes toLeft {
            0% {
                opacity: 0;
                transform: translateX(-10px);
            }
            100% {
                opacity: 1;
                transform: translateX(0px);
            }
        }

        @keyframes toright {
            0% {
                opacity: 0;
                transform: translateX(10px);
            }
            100% {
                opacity: 1;
                transform: translateX(0px);
            }
        }

        .input-box {
            padding: 0 0.5rem;
            position: fixed;
            bottom: 0;
            width: 100%;
            /*height: 1.5rem;*/
        }


        .btn {
            height: 1.5rem;
            min-width: 4rem;
            background: #e0e0e0;
            font-size: 0.88rem;
            color: white;
            text-align: center;
            border-radius: 0.2rem;
            transition: 0.5s;

        }

        .btn-active {
            background: #409eff;
        }
.myTalk{
    color: #2baee9;
}
        .otherTalk{
            color:black;
        }
    </style>
</head>
<body>
<script th:inline="javascript" type="text/javascript">
    const wsPort = [[${wsPort}]];
    const wsPath = [[${wsPath}]];
</script>
<script src="../js/chat/index.js" type="text/javascript"></script>
<div id="app">
    <div class="chat-box">
        <header>聊天室人数：{{onlineUserCount}}</header>
        <div class="msg-box" id="msgBox">
            <div v-for="item in messageList">
                <div><span :class="(item.fromId==sessionStorage.getItem('username')?'myTalk':'otherTalk')">{{item.fromId}}</span>:{{item.message}}</div>
            </div>
        </div>
        <div class="input-box">
            <i-form :model="formItem" inline ref="formItem"  @submit.native.prevent ="return false;" @keyup.enter.native="sendMsg">
                <i-form-item label="Text" prop="message">
                    <i-row>
                        <i-col span="20">
                            <i-input clearable id="message" placeholder="输入..." type="text"
                                     v-model="formItem.message" ></i-input>
                        </i-col>
                        <i-col span="4">
                            <i-button @click="sendMsg"  style="width: 100%;" type="primary">发送</i-button>
                        </i-col>
                    </i-row>
                </i-form-item>
            </i-form>
        </div>
    </div>
</div>
<script th:inline="javascript" type="text/javascript">
    let App = {
        el: '#app',
        data() {
            return {
                formItem: {
                    message: '',
                },
                username: '',
                messageList: [],
                onlineUserCount:0
            }
        },
        watch: {},
        created() {
            initWebChat();
         this.initContract();


        },
        updated:function(){
            this.$nextTick(function(){
                var div = document.getElementById('msgBox');
                div.scrollTop = div.scrollHeight;
            })
        },
        mounted() {
            if (socket) {
                socket.onmessage = this.socketMessage;
            }
            this.username = username;
console.log(username)
        },
        destroyed() {
            if (socket) {
                socket.onclose = this.socketClose;
            }
        },
        methods: {

            getUrlParam(attr) {
                var reg = new RegExp("(^|&)" + attr + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) return unescape(r[2]);
                return null;
            },
            async initContract() {
                let onlineUsers = [];
                try {
                    let res = await this.queryOnlineUsers();
                    onlineUsers = res.data;
                    this.onlineUserCount = res.data.userCount;
                } catch (err) {
                    console.log(err);
                }
                console.log(onlineUsers);
            },
            queryOnlineUsers() {
                // this.$Loading.start();
                return new Promise((resolve, reject) => {
                    axios.get('/chat/onlineUsers', {
                        params: {'_': new Date().getTime(), "selfUsername": this.username}
                    }).then((res) => {
                        // this.$Loading.finish();
                        resolve(res);
                    }).catch((err) => {
                        reject(err);
                    })
                });


            },
            initChat() {
                if (this.socket) {
                    // this.socket.onopen = this.socketOpen;
                    this.socket.onmessage = this.socketMessage;
                    this.socket.onclose = this.socketClose;
                }
            },
            socketOpen(event) {
                if (this.socket) {
                    console.log(event.data)
                }

            },
            socketMessage(event) {
                if (socket) {
                    var resp = event.data;
                    var content = JSON.parse(resp);
                    console.log(content);
                    var fromId = content.fromId;
                    var message = content.message;
                    if (content.type == "1") {
                        if(fromId!==this.username){
                            this.$Message.info(message, 10);
                        }

                    } else {
                        this.messageList.push(content);
                    }

                }
                this.initContract();
            },
            socketClose(event) {
                console.log(event)
            },
            sendMsg() {
                console.log(socket);
                console.log(this.formItem);
                if (!socket) {
                    return;
                }
                if (!this.formItem.message) {
                    document.getElementById("message").focus();
                    this.$Notice.warning({
                        title: '消息为空！！！',
                    });
                    return;
                }
                let fromId = this.username;
                let toId = sessionStorage.getItem("toId") || "";
                let content = {"fromId": this.username, "message": this.formItem.message, "toId": toId};
                if (socket.readyState == WebSocket.OPEN) {
                    socket.send(JSON.stringify(content));
                    this.formItem.message = "";
                } else {
                    alert("连接没有建立成功！");
                }

            },
        },

    };
    let Component = Vue.extend(App);
    new Component().$mount(App.el);
</script>
</body>
</html>